# -*- coding: utf-8 -*-
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db

from emof import core as EMOF
from emof import dumper
from emof import loader

from model import Model

class LoadPackageData(webapp.RequestHandler):
    def get(self):
        m_id = self.request.get("m_id")
        pkg_id = self.request.get("id")
        model = Model.get(m_id)

        rep = loader.Loader().load(model.model_XMI)
        self.response.headers['Content-Type'] = 'application/xml'
        xml = "<r></r>"
        
        pkg = rep.findPackage(pkg_id)
        
        template_values = {'id': pkg_id,
                           'pkg': pkg}

        path = os.path.join(os.getcwd(), 'xml/Package.xml')
        xml = template.render(path, template_values)

        self.response.out.write(xml)
                
class SavePackageData(webapp.RequestHandler):
    def post(self):
        m_id = self.request.get("m_id")
        pkg_id = self.request.get("id")
        name = self.request.get("name")
        uri = self.request.get("uri")
        
        model = Model.get(m_id)

        rep = loader.Loader().load(model.model_XMI)

        pkg = rep.findPackage(pkg_id)
        pkg.name = name
        pkg.uri = uri
        model.model_XMI = dumper.Dumper().dump(rep)
        model.put()
                
        self.response.out.write("OK")
        
class CreatePackageData(webapp.RequestHandler):
    def get(self):
        m_id = self.request.get("m_id")
        
        if self.request.get("p_id") != "":
            p_id = self.request.get("p_id")
        else:
            p_id = '-1'
            
        model = Model.get(m_id)

        rep = loader.Loader().load(model.model_XMI)
        fact = EMOF.Factory(rep)
        pkg2 = fact.create_Package()
        pkg2.name = 'New Package'
        
        pkg = rep.findPackage(p_id)
        
        if pkg:
            pkg.nestedPackage.append(pkg2)
            pkg2.nestingPackage = pkg
        model.model_XMI = dumper.Dumper().dump(rep)
        model.put()

                
        self.response.out.write(pkg2.id + '$$$$' + pkg2.name)